package com.liuyi.usercenterservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuyi.usercenterservice.common.BaseResponse;
import com.liuyi.usercenterservice.common.Commons;
import com.liuyi.usercenterservice.common.ErrorCode;
import com.liuyi.usercenterservice.common.ResultUtils;
import com.liuyi.usercenterservice.entity.domain.User;
import com.liuyi.usercenterservice.entity.request.LoginRequest;
import com.liuyi.usercenterservice.entity.request.RegisterRequest;
import com.liuyi.usercenterservice.entity.request.SearchRequest;
import com.liuyi.usercenterservice.entity.vo.UserVO;
import com.liuyi.usercenterservice.exception.BusinessException;
import com.liuyi.usercenterservice.service.UserService;
import com.liuyi.usercenterservice.service.impl.UserServiceImpl;
import com.liuyi.usercenterservice.tools.SetQueryUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liuyi
 * @since 2024-03-16
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody RegisterRequest register) {
        String userAccount = register.getUserAccount();
        String userPassword = register.getUserPassword();
        String checkPassword = register.getCheckPassword();
        //1.校验
        if (StringUtils.isAnyBlank(userAccount, userAccount, checkPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4 || userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "确认密码与密码不一致");
        }
        return ResultUtils.success(userService.userRegister(userAccount, userPassword, checkPassword));
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody LoginRequest login, HttpServletRequest request) {
        String userAccount = login.getUserAccount();
        String userPassword = login.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(SearchRequest searchRequest, HttpServletRequest request) throws IllegalAccessException {
        //1.鉴权
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //2.查询
        User condition = new User();
        BeanUtils.copyProperties(searchRequest,condition);
        QueryWrapper<User> queryWrapper = SetQueryUtils.setLike(condition);
        //3.脱敏
        List<User> users = userService.list(queryWrapper)
                .stream().map(user -> userService.getSafeUser(user)).collect(Collectors.toList());
        return ResultUtils.success(users);
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateUserById(@RequestBody User user,HttpServletRequest request){
        //1.鉴权
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return ResultUtils.success(userService.updateById(user));
    }
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserById(@RequestParam Long id, HttpServletRequest request) {
        //1.鉴权
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //2.删除
        return ResultUtils.success(userService.removeById(id));
    }

    @GetMapping("/currentUser")
    public BaseResponse<User> getCurrnetUser(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(UserServiceImpl.USER_STATUS);
        return ResultUtils.success(user);
    }
    @GetMapping("/refreshCurrentUser")
    public void refreshCurrentUser(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(UserServiceImpl.USER_STATUS);
        if (user != null){
            request.getSession().setAttribute(UserServiceImpl.USER_STATUS,userService.getById(user.getId()));
        }
    }

    @GetMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(UserServiceImpl.USER_STATUS);
        return ResultUtils.success(true);
    }
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tags,HttpServletRequest request){
        //1.鉴权
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (CollectionUtils.isEmpty(tags)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> users = userService.searchUsersByTags(tags);
        return ResultUtils.success(users);
    }
    @PostMapping("/updateUser")
    public BaseResponse<Integer> updateUser(@RequestBody User user , HttpServletRequest request){
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        int result = userService.updateUserById(user,loginUser);
        return ResultUtils.success(result);
    }
    @GetMapping("/recommend")
    public BaseResponse<List<User>> recommendUser(Long pageNum , Long pageSize,HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (pageNum == null || pageNum < 0){
            pageNum = Long.valueOf(Commons.DEFAULT_PAGE_NUM);
        }
        if (pageSize == null || pageSize < 0){
            pageSize = Long.valueOf(Commons.DEFAULT_PAGE_SIZE);
        }
        List<User> users = userService.recomendUser(loginUser,new Page<User>(pageNum,pageSize));
        return ResultUtils.success(users);
    }
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(Long pageNum , Long pageSize, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (pageNum == null || pageNum < 0){
            pageNum = Long.valueOf(Commons.DEFAULT_PAGE_NUM);
        }
        if (pageSize == null || pageSize < 0){
            pageSize = Long.valueOf(Commons.DEFAULT_PAGE_SIZE);
        }
        List<User> users = userService.matchUser(loginUser,new Page<User>(pageNum,pageSize));
        return ResultUtils.success(users);
    }
}

